package com.briup.prs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

public class Step2  extends Configured implements Tool {

    public static  class  Step2Mapper extends Mapper<Text,Text,Text,Text>{
        /**
         *
         * @param key  userId:shopId
         * @param value 偏好值
         * @param context
         * @throws IOException
         * @throws InterruptedException
         * 输出的k2：ShopId
         * 输出的v2：UsesId:偏好值
         */
        @Override
        protected void map(Text key, Text value, Context context) throws IOException, InterruptedException {
            String[] userAndShop = key.toString().split("[:]");
            context.write(new Text(userAndShop[1]),new Text(userAndShop[0]+":"+value.toString()));
        }
    }
    public  static  class  Step2Reducer extends Reducer<Text,Text,Text,Text>{
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            String s="";
            for (Text value : values) {
                s+=value.toString()+",";
            }
//            截取字符串
            s=s.substring(0,s.length()-1);
            context.write(key,new Text(s));
        }
    }
    @Override
    public int run(String[] args) throws Exception {

        Configuration conf = getConf();
        String in = conf.get("in");
        String out = conf.get("out");

        Job job = Job.getInstance(conf);
        job.setJobName("Step2");
        job.setJarByClass(this.getClass());

        job.setInputFormatClass(KeyValueTextInputFormat.class);
        KeyValueTextInputFormat.addInputPath(job,new Path(in));
        job.setMapperClass(Step2Mapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        job.setReducerClass(Step2Reducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        TextOutputFormat.setOutputPath(job,new Path(out));
        return job.waitForCompletion(true)?0:-1;
    }

    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Step2(),args);
    }
}
